package org.wevil.service.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.wevil.enumu.ResultEnum;
import org.wevil.util.HttpUtil;
import org.wevil.vo.Result;
import org.wevil.vo.pay.PaypalErrorVo;
import org.wevil.vo.pay.PaypalOrderVo;
import org.wevil.vo.pay.PaypalTokenVo;

import java.util.HashMap;
import java.util.Map;

/**
 * paypal支付服务
 */
@Service
public class PaypalService {

    /**
     * paypal服务uri，沙箱环境
     * */
    private final String PAYPAL_BASE_URI = "https://api-m.sandbox.paypal.com";

    /**
     * 获取token地址
     * */
    private final String GET_TOKEN_URL = "/v1/oauth2/token";

    /**
     * 创建订单地址
     * */
    private final String CREATE_ORDER_URL = "/v2/checkout/orders";

    /**
     * 上海的client id - 沙盒环境
     * */
    private final String CLIENT_ID_CN = "AYZrs4L9PZNw1BKe9xhcMLMimvw6NwYlkUoSkHSZKS45z9QbubZpSzBvSstXA7_Ct8fAyRlllxn1ZXiQ";

    /**
     * 上海的secret - 沙盒环境
     * */
    private final String SECRET_CN = "EIxTbkQBjxgoSU9t4qSu3EtDAkciELvmUXO5d06z1l8QX2iYtpeoCglsEMX1iPhodhBQZBUgGjcOuRS2";

    /**
     * 创建订单，返回paypal订单id
     * */
    public Result<String> createOrder() {
        // 获取token
        String url = PAYPAL_BASE_URI+GET_TOKEN_URL;
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("grant_type", "client_credentials");
        String result = HttpUtil.doPostByBasicAuth(url, CLIENT_ID_CN, SECRET_CN, paramMap);
        // 如果报错
        if(result.contains("error_description")){
            PaypalErrorVo paypalErrorVo = JSON.parseObject(result, PaypalErrorVo.class);
            return Result.info(ResultEnum.PARAMS, paypalErrorVo.getError(), paypalErrorVo.getError_description());
        }
        // 解析token对象
        PaypalTokenVo tokenVo = JSON.parseObject(result, PaypalTokenVo.class);
        String token = tokenVo.getAccess_token();

        // 创建订单
        url = PAYPAL_BASE_URI+CREATE_ORDER_URL;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("intent", "CAPTURE");
        JSONArray purchaseUnits = new JSONArray();
        JSONObject purchaseUnit = new JSONObject();
        purchaseUnit.put("custom_id", System.currentTimeMillis());
        JSONObject amount = new JSONObject();
        amount.put("currency_code", "JPY");
        amount.put("value", "15000");
        purchaseUnit.put("amount", amount);
        purchaseUnits.add(purchaseUnit);
        jsonObject.put("purchase_units", purchaseUnits);
        String orderResult = HttpUtil.doPostByBearerToken(url, token, jsonObject.toJSONString());
        // 如果报错
        if(orderResult.contains("error_description")){
            PaypalErrorVo paypalErrorVo = JSON.parseObject(orderResult, PaypalErrorVo.class);
            return Result.info(ResultEnum.PARAMS, paypalErrorVo.getError(), paypalErrorVo.getError_description());
        }
        // 解析订单对象
        PaypalOrderVo orderVo = JSON.parseObject(orderResult, PaypalOrderVo.class);
        return Result.success(orderVo.getId());
    }
}
